package com.controller;

import com.entity.Book;
import com.entity.RequestParam;
import com.mapper.BookMapper;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.service.BookService;
import org.springframework.web.multipart.MultipartFile;
import utils.Result;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import static utils.ExcelReader.readFile;

@RestController
@RequestMapping("/book")
public class IndexController {

    @Autowired
    private BookService bookService;

    @Autowired
    private BookMapper bookMapper;

    @RequestMapping("/login")
    public Result login(String username, String password) {
        Result result= new Result();
        result.setSuccess(true);
        return result;
    }

    @RequestMapping("/list")
    public Result getList(RequestParam req) {
        Result result = new Result();
        result = bookService.queryBooks(req);
        result.setSuccess(true);
        return result;
    }

    @RequestMapping("/detail")
    public Result detail(Integer id) {
        Result result = new Result();
        Book book = bookService.queryBookOne(id);
        result.setData(book);
        result.setSuccess(true);
        return result;
    }

    @RequestMapping("/delete")
    public Result delete(Integer id) {
        Result result = new Result();
        bookService.deleteBookOne(id);
        result.setSuccess(true);
        return result;
    }

    @RequestMapping("/update")
    public Result update(@RequestBody Book book) {
        Result result = new Result();
        bookService.update(book);
        result.setSuccess(true);
        return result;
    }

    @RequestMapping("/save")
    public Result save(@RequestBody Book book) {
        Result result = new Result();
        bookService.save(book);
        result.setSuccess(true);
        return result;
    }

    @RequestMapping("/importBook")
    public Result importBook(@org.springframework.web.bind.annotation.RequestParam("file") MultipartFile file) throws IOException {
        Result result = new Result();
        String destinationPath = System.getProperty("java.io.tmpdir")+ file.getName() + ".xlsx";
        InputStream is = new FileInputStream(convert(file,destinationPath));
        List<String[]> list = readFile(is, 1, null);
        List<Book> books = new ArrayList<>();
        for (String[] row : list) {
            Book book = new Book();
            book.setBookname(row[0]);
            book.setBookcounts(row[1]);
            book.setDetail(row[2]);
            book.setType((byte) 1);
            books.add(book);
        }
        bookService.importBook(books);
        result.setSuccess(true);
        return result;
    }

    public static File convert(MultipartFile multipartFile, String destinationPath) throws IOException, IOException {
        // 创建目标文件对象
        File destFile = new File(destinationPath);

        // 确保目标文件的父目录存在
        File parentDir = destFile.getParentFile();
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }

        // 将MultipartFile的内容传输到目标文件
        multipartFile.transferTo(destFile);

        // 返回转换后的File对象
        return destFile;
    }

    @RequestMapping("/exportBook")
    public void exportBook(HttpServletResponse response) throws IOException {
        RequestParam req = new RequestParam();
        req.setCurrent(0);
        req.setSize(100);
        List<Book> books = bookMapper.queryBooks(req);
        if (CollectionUtils.isEmpty(books)) {
            return ;
        }
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Data");
        // 创建表头
        Row headerRow = sheet.createRow(0);
        String[] columns = {"序列号", "书名", "数量", "描述", "类型", "时间"}; // 根据你的数据模型调整
        for (int i = 0; i < columns.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(columns[i]);
        }
        // 填充数据
        int rowNum = 1;
        for (Book book : books) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(book.getBookid());
            row.createCell(1).setCellValue(book.getBookname());
            row.createCell(2).setCellValue(book.getBookcounts());
            row.createCell(3).setCellValue(book.getDetail());
            row.createCell(4).setCellValue(book.getType());
            row.createCell(5).setCellValue(book.getDate());
        }

        // 设置响应头
        response.setContentType("octets/stream");
        response.addHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.addHeader("Content-Disposition", "attachment; filename=data.xlsx");
        // 写入响应输出流
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
        }
    }
}
